﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Threading;

namespace SiteMonitorLogic
{
    public sealed class CheckRunner
    {
        /// <summary>
        /// Event delegate for the StatusUpdate event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public delegate void CheckCompleteDelegate(object sender, CheckCompleteEventArgs e);

        /// <summary>
        /// Triggered when a check's status has changed.
        /// </summary>
        public event CheckCompleteDelegate CheckComplete;

        /// <summary>
        /// Construct a new check runner.
        /// </summary>
        /// <param name="configDocument"></param>
        public CheckRunner()
        {
            
        }

        /// <summary>
        /// Loads the config from the given xml element
        /// </summary>
        /// <param name="config"></param>
        public void Execute(XElement config)
        {
            // run each check in sequence
            foreach (XElement element in config.Elements())
            {
                ICheck check = null;
                try
                {
                    check = LoadCheck(element);
                    CheckResult result = check.Execute();
                    CheckComplete(this, new CheckCompleteEventArgs() { Check = check, Result = result });
                }
                catch (Exception ex)
                {
                    CheckResult result = new CheckResult();
                    CheckCompleteEventArgs ev = new CheckCompleteEventArgs();
                    ev.Check = check;
                    ev.Result = new CheckResult() { Message = "Error executing check: " + element.Name + ", " + ex.ToString(), ResultCode = CheckResultCode.Failed };
                    CheckComplete(this, ev);
                }
            }
        }

        private ICheck LoadCheck(XElement element)
        {
            if (element.Name == "ContentCheck")
            {
                return new ContentCheck(element);
            }
            else
                throw new NotSupportedException("Unknown check type: " + element.Name);
        }
    }
}
